package com.magic.gre.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.magic.gre.R;
import com.magic.gre.base.activity.BaseMVPActivity;
import com.magic.gre.entity.ActivityBean;
import com.magic.gre.helper.Contract;
import com.magic.gre.mvp.contract.ActivityDetailsContract;
import com.magic.gre.mvp.presenter.ActivityDetailsPresenterImpl;
import com.magic.gre.ui.dialog.AvtivityDialog;
import com.magic.gre.ui.dialog.ShareDialog;
import com.noname.lib_base_java.util.PathUtil;
import com.noname.lib_base_java.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: Lmoumou
 * Date: 2019-01-10 09:44
 * 文件名: ActivityDetailsActivity
 * 描述:
 */
public class ActivityDetailsActivity extends BaseMVPActivity<ActivityDetailsPresenterImpl> implements ActivityDetailsContract.View,
        AvtivityDialog.OnActivityDialogListener {

    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.signup_tv)
    TextView signupTv;

    public static void startThis(Context context, ActivityBean bean, String activityId, boolean isSelf) {
        Intent intent = new Intent(context.getApplicationContext(), ActivityDetailsActivity.class);
        intent.putExtra("ActivityBean", bean);
        intent.putExtra("isSelf", isSelf);
        intent.putExtra("activityId", activityId);
        context.startActivity(intent);
    }

    private String activtyId;
    private boolean isSelf;
    private ActivityBean bean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_details_activity;
    }

    @Override
    protected ActivityDetailsPresenterImpl creatPresenter() {
        return new ActivityDetailsPresenterImpl(this);
    }

    @Override
    protected void netOverride() {

    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        isSelf = getIntent().getBooleanExtra("isSelf", false);
        bean = getIntent().getParcelableExtra("ActivityBean");
        activtyId = getIntent().getStringExtra("activityId");

        signupTv.setVisibility(isSelf ? View.GONE : bean.getType() == 1 ? View.VISIBLE : View.GONE);

        initWebView();
    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);

        webSettings.setBlockNetworkImage(false);//解决图片不显示
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

//        webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
        webView.loadUrl(PathUtil.urlPath(bean.getDataUrl()));
//        webView.loadUrl("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#en/zh/ok");

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                webView.loadUrl("javascript:(function(){" +
                        "var objs = document.getElementsByTagName('img'); " +
                        "for(var i=0;i<objs.length;i++)  " +
                        "{"
                        + "var img = objs[i];   " +
                        "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                        "}" +
                        "})()");
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        webView.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

    }

    @OnClick(value = {R.id.signup_tv, R.id.right_tv})
    protected void onClick(View view) {
        switch (view.getId()) {
            case R.id.signup_tv:
                AvtivityDialog dialog = new AvtivityDialog();
                dialog.setOnActivityDialogListener(this);
                dialog.showThis(getSupportFragmentManager(), AvtivityDialog.class.getSimpleName(), activtyId, bean.getApplyImage());
                break;
            case R.id.right_tv:
                if (bean != null) {
                    ShareDialog shareDialog = new ShareDialog();
                    shareDialog.showThis(getSupportFragmentManager(), ShareDialog.class.getSimpleName(),
                            bean.getTitle(),
                            bean.getPlainContent(),
                            PathUtil.urlPath(bean.getDataUrl()),
                            PathUtil.imgPath(bean.getCoverImage()));
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
    }

//    @Override
//    public void vActDetails(ActivityBean bean) {
//        this.bean = bean;
////        webView.loadUrl(PathUtil.urlPath(bean.getDataUrl()));
//    }

    @Override
    public void vActApply() {
        ToastUtil.getInstance().showNormal(this, "报名成功");
    }

    @Override
    public void onSingUp(String activityId, String wechatNum) {
        mPresenter.pActApply(activityId, wechatNum);
    }

    @Override
    public void onQA() {
        WebActivity.startThis(this, "", Contract.QA_URL);
    }
}
